package alibaba.java8datetimeapi;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.junit.jupiter.api.Test;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.*;

/**
 * @author ChangLiang
 * @date 2020/4/17
 */
public class Java8ApiTest {

    /**
     * use threadFactoryBuilder to define a thread pool
     */
    private static ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();

    private static ExecutorService pool = new ThreadPoolExecutor(5, 200, 0L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());

    private static CountDownLatch countDownLatch = new CountDownLatch(100);

    @Test
    public void test() {
        // Date convert to String
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String dateStr = now.format(formatter);
        System.out.println(dateStr);

        // String convert to Date
        LocalDate parse = LocalDate.parse(dateStr, formatter);

    }

    @Test
    public void test1() throws InterruptedException {

        Set<String> dates = Collections.synchronizedSet(new HashSet<>());
        for (int i = 0; i < 100; i++) {
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            int finalI = i;
            pool.execute(()->{
                // immutable Object 不可变对象 应该与ThreadLocal一样 都是线程内 这个scope 的对象 只是一个是ThreadLocal对象 另一个是不可变对象
                // 参考 小马哥 spring核心编程思想 85丨自定义Bean作用域：设计Bean作用域应该注意哪些原则？
                LocalDateTime plusDay = now.plusDays(finalI);
                String dateString = plusDay.format(formatter);
                dates.add(dateString);
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        System.out.println(dates.size());
        ArrayList list = Util.convertToSortedArrayList(dates);
        System.out.println(list);
    }
}
